package com.pie4cloud.pie.job.executor.mapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;


@Repository
public class CommonRepository {

	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private static final String BASE_INSERT_SQL = "INSERT INTO %s(%s) VALUES(%s)";
	
	public void InsertOneRecored(Map<String, String> data,String tableName) {
		
		Set<String> colSet = data.keySet();
		String cols = getCols(colSet);
		String sql = String.format(BASE_INSERT_SQL, tableName,cols,getPrepared(colSet));
		jdbcTemplate.execute(sql, new CommonPreparedStatementCallBack(data, cols.split(",")));
	}
	
	private static String getCols(Set<String> colSet) {
		return StringUtils.join(colSet,",");
	}
	
	private static String getPrepared(Set<String> colSet) {

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < colSet.size(); i++) {
			list.add("?");
		}
		return StringUtils.join(list,",");
	}
}
